package com.hjm.friend.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hjm.common.core.domain.page.TableDataInfo;
import com.hjm.friend.domain.question.Question;
import com.hjm.friend.domain.question.QuestionES;
import com.hjm.friend.domain.question.dto.QuestionQueryDTO;
import com.hjm.friend.domain.question.vo.QuestionDetailVO;
import com.hjm.friend.domain.question.vo.QuestionVO;
import com.hjm.friend.elasticsearch.QuestionRepository;
import com.hjm.friend.manage.QuestionCacheManager;
import com.hjm.friend.mapper.question.QuestionMapper;
import com.hjm.friend.service.question.QuestionService;
import com.hjm.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class QuestionServiceImpl implements QuestionService {


    @Autowired
    QuestionRepository  questionRepository;

    @Autowired
    QuestionMapper questionMapper;

    @Autowired
    QuestionCacheManager questionCacheManager;

    @Autowired
    RedisService redisService;


    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        // 先看 redis 中是否存在 数据
        long count = questionRepository.count();
        if(count <=0 ){
            // 无数据 ， 进行刷新（从数据库中进行获取）
            refreshQuestion();
        }

        // 现在 redis 中 存储了 从 数据库 中获取的完整数据

        Integer difficulty = questionQueryDTO.getDifficulty();
        String keyword = questionQueryDTO.getKeyword();

        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable= PageRequest.of(questionQueryDTO.getPageNum()-1,questionQueryDTO.getPageSize(),sort);

        Page<QuestionES> questionVOPage;
        if(difficulty == null && StrUtil.isEmpty(keyword)){
            questionVOPage = questionRepository.findAll(pageable);
        } else if (difficulty == null) {
            questionVOPage = questionRepository.findByTitleOrContent(keyword,keyword,pageable);
        } else if (StrUtil.isEmpty(keyword)) {
            questionVOPage = questionRepository.findQuestionByDifficulty(difficulty,pageable);
        }else{
            questionVOPage = questionRepository.findByTitleOrContentAndDifficulty(keyword, keyword, difficulty, pageable);
        }
        long total = questionVOPage.getTotalElements();
        if(total <=0 ){
            return TableDataInfo.empty();
        }
        // 有数据，但是我又不想 全部都返回, 定义一个 vo 专门进行数据返回
        List<QuestionVO> questionVOList;
        questionVOList = BeanUtil.copyToList(questionVOPage.getContent(),QuestionVO.class);
        return TableDataInfo.success(questionVOList,total);
    }


    @Override
    public QuestionDetailVO detail(Long questionId) {
        // 从 es 中 查询数据
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        // 如果存在数据
        if(BeanUtil.isNotEmpty(questionES)){
            BeanUtil.copyProperties(questionES,questionDetailVO);
            return questionDetailVO;
        }
        // 不存在数据, 进行缓存刷新
        Question question = questionMapper.selectById(questionId);
        if(BeanUtil.isEmpty(question)){
            return null;
        }
        questionCacheManager.refreshCache();

        BeanUtil.copyProperties(question,questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public String preQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if( listSize == null || listSize <=0  ){
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.preQuestion(questionId).toString();
    }

    @Override
    public String nextQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if(listSize == null || listSize <=0   ){
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.nextQuestion(questionId).toString();

    }


    private void refreshQuestion() {
        // 从数据库中 进行获取
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>());

        if(CollectionUtil.isEmpty(questionList)){
            return ;
        }

        // 从数据库中 获取到 数据 后 同步到 elasticSearch 中
        List<QuestionES> questionVOList = BeanUtil.copyToList(questionList, QuestionES.class);
        questionRepository.saveAll(questionVOList);

    }

}
